package com.hsy.managemoney.modules.web;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.common.DPBusEvent;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPPicassoUtil;
import com.deparse.dpframe.utils.DPUnitUtil;
import com.hsy.managemoney.R;
import com.hsy.managemoney.modules.common.BaseHaveActionBarActivity;
import com.hsy.managemoney.modules.utils.CommonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by MartinKent on 2016/8/12.
 */
public class DPWebViewActivity extends BaseHaveActionBarActivity implements View.OnClickListener {
    protected ImageView btnBack;
    protected TextView pageTitle;
    protected ImageView btnActImg;
    protected TextView btnActText;
    protected View btnActAncher;
    protected DPWebView webView;

    private WebViewHandler webViewHander;
    private ViewGroup webViewContainer;
    private LayoutInflater inflater;
    private View root;
    private String mid;


    public WebViewHandler getWebViewHander() {
        return webViewHander;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = LayoutInflater.from(this);
        root = inflater.inflate(R.layout.dp_webview_activity, null);
        super.setContentView(R.layout.dp_webview_activity);
        initView();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_back) {
            KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
            webViewHander.dispatchKeyEvent(event);
        }
    }

    private void initView() {
        btnBack = (ImageView) findViewById(R.id.btn_back);
        btnBack.setOnClickListener(DPWebViewActivity.this);
        pageTitle = (TextView) findViewById(R.id.page_title);
        btnActImg = (ImageView) findViewById(R.id.btn_act_img);
        btnActText = (TextView) findViewById(R.id.btn_act_text);
        btnActAncher = findViewById(R.id.btn_act_ancher);
        webView = (DPWebView) findViewById(R.id.web_view);

        webViewContainer = (ViewGroup) findViewById(R.id.web_view_container);

        webViewHander = new WebViewHandler(this);
        webView.setClient(webViewHander);

        Intent intent = getIntent();
        if (intent.hasExtra("url")) {
            String url = intent.getStringExtra("url");
            if (url.contains("?")) {
                url += ("&token=" + CommonUtils.getToken(this));
            } else {
                url += ("?token=" + CommonUtils.getToken(this));
            }
            webView.loadUrl(url);
        } else {
            webView.loadUrl("file:///android_asset/index.html");
        }
        if (intent.hasExtra("type")) {
            //TODO SOMTHING
        } else {
            //TODO NOTHING
        }
        if (intent.hasExtra("title")) {
            setTitle(intent.getStringExtra("title"));
        }
        if (intent.hasExtra("backButtonVisibility")) {
            int v = intent.getIntExtra("backButtonVisibility", View.VISIBLE);
            webViewHander.setViewVisibility(v, btnBack);
        }
    }

    public void startActivity(String url, String type, String title, int backButtonVisibility) {
        Intent intent = new Intent(this, DPWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("type", type);
        intent.putExtra("title", title);
        intent.putExtra("backButtonVisibility", backButtonVisibility);
        super.startActivity(intent);
    }

    public void startActivityForResult(String callback, int reqCode, String url, String type, String title, int backButtonVisibility) {
        Intent intent = new Intent(this, DPWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("type", type);
        intent.putExtra("title", title);
        intent.putExtra("callback", callback);
        intent.putExtra("backButtonVisibility", backButtonVisibility);
        super.startActivityForResult(intent, reqCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        webViewHander.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void setTitle(CharSequence title) {
        pageTitle.setText(title);
    }

    @Override
    public void setTitle(int titleId) {
        pageTitle.setText(getString(titleId));
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        boolean b = false;
        if (null != webViewHander) {
            b = webViewHander.dispatchKeyEvent(event);
        }
        return b || super.dispatchKeyEvent(event);
    }

    private String surlq, titleq;

    private class WebViewHandler extends BaseWebViewHandler {

        private final Activity activity;
        private String keyEventCallback;
        private boolean preventKeyEventDefault = false;
        private View webViewFailurePage;
        private boolean isErrorPage = false;

        public WebViewHandler(@NonNull Activity activity) {
            super(activity);
            this.activity = activity;
        }

        @Override
        public void onReceivedTitle(WebChromeClient client, WebView view, String title) {
            if (!"找不到网页".equals(title)) {
                super.onReceivedTitle(client, view, title);
            }
        }

        @Override
        public void onPageFinished(WebViewClient client, WebView view, String url) {
            super.onPageFinished(client, view, url);
            if (!isErrorPage) {
                getWebView().setVisibility(View.VISIBLE);
            }
            isErrorPage = false;
        }

        @Override
        public void onReceivedError(WebViewClient client, final WebView view, int errorCode, String description, String failingUrl) {
            isErrorPage = true;
            getWebView().setVisibility(View.GONE);
            getWebView().loadUrl("javascript:document.body.innerHTML='';");
//            this.webViewFailurePage = CommonUtils.showNetworkFailure(getWebView().getContext(), webViewContainer, 0, new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (null != webViewFailurePage.getParent()) {
//                        webViewContainer.removeView(webViewFailurePage);
//                    }
            getWebView().reload();
//                }
//            });
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebViewClient client, WebView view, String url) {
//            startActivity(url, "", "", View.VISIBLE);
            view.loadUrl(url);
            return true;
        }

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
                if (null != keyEventCallback) {
                    String cmd = "javascript:" + keyEventCallback + "(" + event.getAction() + ")";
                    getWebView().loadUrl(cmd);
                }
                if (!preventKeyEventDefault && KeyEvent.ACTION_UP == event.getAction()) {
                    if (getWebView().canGoBack()) {
                        getWebView().goBack();
                    } else {
                        onCloseWindow();
                    }
                    return true;
                }
                return true;
            }
            return super.dispatchKeyEvent(event);
        }

        @Override
        protected void onRegisterBackCallback(String callback, boolean preventDefault) {
            this.keyEventCallback = callback;
            this.preventKeyEventDefault = preventDefault;
        }

        @Override
        protected void onOpenWindow(String u, String type, String title, int v) {
            startActivity(u, type, title, v);
        }

        @Override
        protected void onOpenWindowForResult(String callback, int reqCode, String u, String type, String title, int v) {
            startActivityForResult(callback, reqCode, u, type, title, v);
        }

        @Override
        protected void onCloseWindow() {
            finish();
        }

        @Override
        protected void onSetFunctionButtonCallback(String callback, String args) {
            onFunctionButtonClickListener listener = new onFunctionButtonClickListener(webView, callback, args);
            btnActAncher.setOnClickListener(listener);
            btnActImg.setOnClickListener(listener);
            btnActText.setOnClickListener(listener);
        }

        @Override
        protected void onSetFunctionButtonImageVisibility(int visibility) {
            setViewVisibility(visibility, btnActImg);
        }

        @Override
        protected void onSetFunctionButtonImage(Context context, String img) {
            DPPicassoUtil.load(activity, img, btnActImg);
            setViewVisibility(View.VISIBLE, btnActImg, btnActAncher);
            setViewVisibility(View.INVISIBLE, btnActText);
        }

        @Override
        protected void onSetFunctionButtonTextVisibility(int visibility) {
            setViewVisibility(visibility, btnActText);
        }

        @Override
        protected void onSetFunctionButtonText(String text) {
            btnActText.setText(text);
            setViewVisibility(View.VISIBLE, btnActText, btnActAncher);
            setViewVisibility(View.INVISIBLE, btnActImg);
        }

        @Override
        protected void onSetBackButtonVisibility(int visibility) {
            setViewVisibility(visibility, btnBack);
        }

        @Override
        protected void onSetTitle(String title) {
            setTitle(title);
        }

        @Override
        protected void onSetFunctionButtonVisibility(int visibility) {
            setViewVisibility(visibility, btnActAncher);
        }

        @Override
        protected void onSetFunctionButtonClickable(boolean clickable) {
            super.onSetFunctionButtonClickable(clickable);
            btnActAncher.setClickable(clickable);
            btnActText.setClickable(clickable);
            btnActImg.setClickable(clickable);
        }

        @Override
        protected void onShowDropDownMenu(final JSONArray array, final String callback) {
            final DropDownMenuAdapter menuAdapter = new DropDownMenuAdapter(array);
            final ListPopupWindow popupWindow = new ListPopupWindow(DPWebViewActivity.this);
            popupWindow.setWidth(DPUnitUtil.dip2px(DPWebViewActivity.this, 100));
            popupWindow.setAdapter(menuAdapter);
            popupWindow.setModal(true);
            popupWindow.setAnchorView(btnActAncher);
            if (!TextUtils.isEmpty(callback)) {
                popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String url = "javascript:" + callback + "(" + position + ",\"" + menuAdapter.getLabel(position) + "\",\"" + menuAdapter.getValue(position) + "\");";
                        DPLogUtil.d(url);
                        webView.loadUrl(url);
                        popupWindow.dismiss();
                    }
                });
            }
            popupWindow.show();
        }

        @Override
        protected void onShowShare(String title, String content, String url, String imgUrl, String surl) {

            DPLogUtil.d("onShowShare", "title=" + title + "  content=" + content + "  url=" + url + "  imgUrl=" + imgUrl + "  surl=" + surl);
        }


        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (null == data) {
                return;
            }
            String cmd = "javascript:" + data.getStringExtra("callback") + "(" + requestCode + "," + resultCode + ",'" + data.getStringExtra("webview_data") + "')";
            DPLogUtil.d("onActivityResult cmd=" + cmd);
            getWebView().loadUrl(cmd);
        }

        @Override
        protected void onFinish(String data) {
            Intent intent = new Intent();
            intent.putExtra("webview_data", data);
            intent.putExtra("callback", getIntent().getStringExtra("callback"));
            setResult(RESULT_OK, intent);
            finish();
        }

        private class onFunctionButtonClickListener implements View.OnClickListener {
            private final WebView webView;
            private final String callback;
            private final String args;

            public onFunctionButtonClickListener(@NonNull WebView webView, @NonNull String callback, @Nullable String args) {
                this.webView = webView;
                this.callback = callback;
                this.args = args;
            }

            @Override
            public void onClick(View v) {
                String cmd;
                if (TextUtils.isEmpty(args)) {
                    cmd = "javascript:" + callback + "();";
                } else {
                    cmd = "javascript:" + callback + "('" + args + "');";
                }
                DPLogUtil.d("onFunctionButtonClickListener.onClick callback=" + callback + ",args=" + args + ",url=" + cmd);
                webView.loadUrl(cmd);
            }
        }
    }

    private class DropDownMenuAdapter extends BaseAdapter {
        private final JSONArray data;

        public DropDownMenuAdapter(JSONArray data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.length();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public String getLabel(int position) {
            try {
                JSONObject object = data.getJSONObject(position);
                if (object.has("label")) {
                    return object.getString("label");
                }
            } catch (JSONException e) {

            }
            return null;
        }

        public String getValue(int position) {
            try {
                JSONObject object = data.getJSONObject(position);
                if (object.has("value")) {
                    return object.getString("value");
                }
            } catch (JSONException e) {

            }
            return null;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView;
            if (null == convertView) {
                textView = new TextView(DPWebViewActivity.this);
                textView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DPUnitUtil.dip2px(DPWebViewActivity.this, 30)));
                textView.setGravity(Gravity.CENTER_VERTICAL);
                textView.setPadding(DPUnitUtil.dip2px(DPWebViewActivity.this, 15), 0, 0, 0);
            } else {
                textView = (TextView) convertView;
            }
            textView.setText(getLabel(position));
            return textView;
        }
    }
}